#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include "serial_recv.h"
#include <stdbool.h>
#include <stdint.h>

// 定义串口与CAN通道的映射配置
typedef struct {
    char *device_path;  // 串口设备路径
    int baudrate;       // 波特率
    uint8_t can_channel; // 对应的CAN通道号
    bool running;       // 线程运行状态
} SerialCanConfig;

// 线程函数：为每个串口端口创建独立的发送线程
void* serial_send_thread(void* arg) {
    SerialCanConfig *config = (SerialCanConfig*)arg;
    
    // 打开串口
    int fd = open_serial(config->device_path, get_baud_rate(config->baudrate));
    if (fd < 0) {
        printf("Failed to open serial port: %s\n", config->device_path);
        return NULL;
    }
    
    // 根据CAN通道号选择对应的发送缓冲区
    unsigned char send_buf[12];
    memset(send_buf, 0, sizeof(send_buf));
    
    // 构建特定通道的数据包（根据实际需求调整）
    send_buf[0] = 0x01;
    send_buf[1] = 0x00;
    send_buf[2] = config->can_channel;  // 通道号
    send_buf[11] = 0x0A; // 示例数据

    
    int send_len = sizeof(send_buf);
    
    // 循环发送数据
    while (config->running) {
        int n = write(fd, send_buf, send_len);
        if (n < 0) {
            perror("write");
            break;
        }
        tcdrain(fd);
        printf("[%s -> CAN%d] Send: ", config->device_path, config->can_channel);
        for (int i = 0; i < send_len; ++i) {
            printf("%02X ", send_buf[i]);
        }
        printf("\n");
        fflush(stdout);
        usleep(500000); // 500ms间隔
    }

    close(fd);
    return NULL;
}

int main(int argc, char *argv[]) {
    if (argc < 4 || (argc-1) % 3 != 0) {
        printf("Usage: %s <serial_dev1> <baudrate1> <can_channel1> [<serial_dev2> <baudrate2> <can_channel2> ...]\n", argv[0]);
        printf("Example: %s /dev/ttyF0 1152000 1 /dev/ttyF1 1152000 2\n", argv[0]);
        return 1;
    }
    
    // 计算配置组数
    int config_count = (argc - 1) / 3;
    SerialCanConfig *configs = malloc(config_count * sizeof(SerialCanConfig));
    pthread_t *threads = malloc(config_count * sizeof(pthread_t));
    
    // 初始化并启动线程
    for (int i = 0; i < config_count; i++) {
        configs[i].device_path = argv[i*3 + 1];
        configs[i].baudrate = atoi(argv[i*3 + 2]);
        configs[i].can_channel = atoi(argv[i*3 + 3]);
        configs[i].running = true;
        
        // 检查波特率是否支持
        speed_t speed = get_baud_rate(configs[i].baudrate);
        if (speed == -1) {
            fprintf(stderr, "Unsupported baudrate: %d for %s\n", configs[i].baudrate, configs[i].device_path);
            return 1;
        }
        
        // 检查CAN通道号是否有效
        if (configs[i].can_channel < 1 || configs[i].can_channel > 4) {
            fprintf(stderr, "Invalid CAN channel: %d (must be 1-4)\n", configs[i].can_channel);
            return 1;
        }
        
        // 创建线程
        if (pthread_create(&threads[i], NULL, serial_send_thread, &configs[i]) != 0) {
            perror("pthread_create");
            return 1;
        }
        printf("Started thread for %s (CAN channel %d) at %d baud\n", 
               configs[i].device_path, configs[i].can_channel, configs[i].baudrate);
    }
    
    // 等待用户输入退出
    printf("Press Enter to stop...\n");
    getchar();
    
    // 停止所有线程
    for (int i = 0; i < config_count; i++) {
        configs[i].running = false;
        pthread_join(threads[i], NULL);
        printf("Stopped thread for %s\n", configs[i].device_path);
    }
    
    free(configs);
    free(threads);
    return 0;
}